<?php

namespace common\models\cms;

use Yii;
use common\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%cms_watch_log}}".
 *
 * @property int $id
 * @property string $model 模型
 * @property int $model_id 模型ID
 * @property int $user_id 用户ID
 * @property string|null $date 日期
 * @property int $duration 观看时长
 * @property int $special_id 专题ID
 * @property int $total 观看总时长
 * @property int $status 在线状态
 * @property int $validated_at 校准时间
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class CmsWatchLog extends \common\db\ActiveRecord {

    const STATUS_ACTIVE = 10;
    const STATUS_DEFAULT = 0;
    //
    const MODEL_VIDEO = 'video';
    const MODEL_AUDIO = 'audio';
    const MODEL_ARTICLE = 'article';

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%cms_watch_log}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['model_id', 'user_id', 'duration', 'special_id', 'total', 'status', 'validated_at', 'created_at', 'updated_at'], 'integer'],
            [['model'], 'required'],
            [['model'], 'string', 'max' => 20],
            [['date'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'model' => '模型',
            'model_id' => '模型ID',
            'user_id' => '用户ID',
            'date' => '日期',
            'special_id' => '专题ID',
            'duration' => '时长',
            'total' => '总时长',
            'status' => '状态',
            'validated_at' => '校准时间',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    public function afterSave($insert, $changedAttributes) {
        parent::afterSave($insert, $changedAttributes);
        if (YII_ENV_PROD && !isset($changedAttributes['total']) && $this->special_id && $this->duration > $this->total) {
            if ($this->status === static::STATUS_DEFAULT) {
                \common\logics\queue\UvsExpQueue::specialGrowUp([
                    'special_id' => $this->special_id,
                    'user_id' => $this->user_id,
                ]);
            }
        }
    }

    public static function articleViews($id, $uid = 0, $specialid = 0) {
        if (!$uid) {
            return;
        }
        $model = static::findOrNew([
            'model' => static::MODEL_ARTICLE,
            'model_id' => $id,
            'user_id' => $uid,
            'date' => date('Y-m-d'),
            'special_id' => $specialid,
        ]);
        if ($model->isNewRecord) {
            $model->duration = 0;
        }
        $model->duration += 1;
        $model->status = static::STATUS_DEFAULT;
        return $model->save();
    }

}
